<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <h1>发布订阅模式</h1>
    <!-- DOM 模板不会识别多个单标签形式的组件 -->
    <foo></foo>
    <hr>
    <bar></bar>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
  <script>
    const bus = new Vue()

    Vue.component('Foo', {
      template: `
        <div>
          <h2>Foo 组件</h2>
          <p>{{ count }}</p>
          <button @click="handleIncrement">+1</button>
        </div>
      `,
      data () {
        return {
          count: 0
        }
      },
      methods: {
        handleIncrement () {
          this.count++
          bus.$emit('increment') // 发布事件
        }
      }
    })

    Vue.component('Bar', {
      template: `
        <div>
          <h2>Bar 组件</h2>
          <p>{{ count }}</p>
          <button @click="handleIncrement">+1</button>
        </div>
      `,
      created () {
        // 订阅事件
        bus.$on('increment', () => {
          this.count++
        })
      },
      data () {
        return {
          count: 0
        }
      },
      methods: {
        handleIncrement () {
          this.count++
        }
      }
    })

    const app = new Vue({
      el: '#app'
    })
  </script>
</body>
</html>
